package com.lz.ui_lib.widget.gif;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executors;

/**
 * 播放GIF的SurfaceView
 * <p>
 * Created by Liuyk on 2015/10/26.
 */
public class GifSurfaceLayout extends BaseSurfaceLayout implements Runnable {
    private static final String TAG = "GifSurfaceLayout";
    //SurfaceView 拥有独立的绘图表面，其UI可以在一个独立的线程中进行绘制，不会占用主线程资源
    //可以实现复杂、高效的UI
    private int mZoom = 1;
    private int mWidth;
    private int mHeight;

    private int mDuration;

    private Movie movie;

    public GifSurfaceLayout(Context context) {
        this(context, null);
    }

    public GifSurfaceLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GifSurfaceLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        try {
            final InputStream in = getContext().getResources().getAssets().open("gif/loading.gif");
            movie = Movie.decodeStream(in);
            mWidth = movie.width();
            mHeight = movie.height();
            mDuration = movie.duration();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(mWidth, mHeight);
    }

    @Override
    public void baseSurfaceCreated(SurfaceHolder holder) {
        Executors.newFixedThreadPool(2).execute(this);
    }

    @Override
    public void baseSurfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void baseSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void run() {
        while (getVisibility() == VISIBLE) {
            Log.i(TAG, "gif...");
            Canvas canvas = mSurfaceHolder.lockCanvas();
            if (canvas == null) {
                return;
            }
            canvas.save();
            canvas.scale(mZoom, mZoom);
            //Movie管理着GIF动画中的多个帧，通过setTime()可以让它在draw()的时候绘出相应的那帧图像。
            //通过当前时间与duration之间的换算关系,实现GIF动起来的效果
            movie.setTime((int) (System.currentTimeMillis() % mDuration));//设置要显示的帧
            movie.draw(canvas, 0, 0);//开始绘制
            canvas.restore();
            mSurfaceHolder.unlockCanvasAndPost(canvas);
        }
    }

    public void setZoom(int zoom) {
        this.mZoom = zoom;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }
}
